from csv import reader

from django.core.urlresolvers import reverse
from django.conf import settings
from django.shortcuts import render_to_response, get_object_or_404
from django.template import RequestContext
from django.http import HttpResponse, HttpResponseRedirect
from django.contrib.auth.models import User

from os.path import join

from crm.forms import *
from crm.models import *

from tagging.models import TaggedItem

def client_form(request, client_id=None):
  if client_id:
    client = get_object_or_404(Client, id=client_id)
  else:
    client = Client()

  if request.POST:    
    form = ClientForm(data=request.POST, instance=client)

    if form.is_valid():
      form.save()
      return HttpResponseRedirect(reverse('crm_client_detail', args=(client.id,)))
    else:
      request.user.message_set.create(message='Please check your data.')
  else:
    form = ClientForm(instance=client)

  return render_to_response('crm_form.html', {'form':form}, context_instance=RequestContext(request))

def organisation_form(request, org_id=None):
  if org_id:
    org = get_object_or_404(Organisation, id=org_id)
  else:
    org = Organisation()

  if request.POST:    
    form = OrganisationForm(data=request.POST, instance=org)

    if form.is_valid():
      form.save()
      return HttpResponseRedirect(reverse('crm_organisation_detail', args=(org.id,)))
    else:
      request.user.message_set.create(message='Please check your data.')
  else:
    form = OrganisationForm(instance=org)

  return render_to_response('crm_form.html', {'form':form}, context_instance=RequestContext(request))

def search_form(request):
    if request.GET:
	term = request.GET['term']
        dict = {}

        clients = Client.objects.filter(tags__contains = term)

        organisations = Organisation.objects.filter(name__contains = term) | Organisation.objects.filter(description__contains = term) | Organisation.objects.filter(tags__contains = term)

        dict['search_term'] = term
        if clients.count() > 0:
          dict['client_list'] = clients     
        if organisations.count() > 0:
          dict['organisation_list'] = organisations

	return render_to_response('crm_search.html', dict, context_instance=RequestContext(request))
    else:
	return render_to_response('crm_search.html', context_instance=RequestContext(request))

def client_import(request):
    '''
    Import client list from a CSV file. The file must be formatted as:
    first name, last name, job title, desacription, Organisation, Email, Phone, tags
    
    There should be no header
    
    This is really a horrible hack right now, but it gets us working. The
    file is not uploaded but must be stored in the CRM application root with
    the name "contacts.csv"
    
    For each line a new user is created with the username "first_name last_name" 
    and password "pwd_LASTNAME". An organisation is created and a role between the
    client and organisation is set up.
    
    No duplicate checks are done at this time so a duplicate client will result
    in an non unique username error, a duplicate organisation will result in two
    organistions being entered.
    '''
    fh = open(join(settings.PROJECT_ROOT, "crm/contacts.csv"))
    table = reader(fh)

    header = table.next()

    for first_name, last_name, title, role_desc, organisation, email, phone, tags in table:
        new_user = User.objects.create_user(username = first_name + '_' + last_name, email = email, password = "pwd_" + last_name)
        new_user.first_name = first_name
        new_user.last_name = last_name
        new_user.save()
        
        new_org = Organisation(name = organisation)
        new_org.tags = tags
        new_org.save()
                
        new_client = Client(user = new_user, owner = request.user, office_phone = phone)
        new_client.tags = tags
        new_client.save()
                
        role = Role()
        role.title = title
        role.description = role_desc
        role.organisation = new_org
        role.client = new_client
        role.save()
    fh.close()
    del table
    
    return HttpResponseRedirect(request.META.get('HTTP_REFERER', ''))


def tagged_client(request, tag_name=None):
  clients = Client.objects.all()

  return render_to_response('crm/client_list.html', {'set': TaggedItem.objects.get_by_model(Client, tag_name)}, context_instance=RequestContext(request))

def tagged_organisation(request, tag_name=None):
  return render_to_response('crm/organisation_list.html', {'set': TaggedItem.objects.get_by_model(Organisation, tag_name)}, context_instance=RequestContext(request))
